# -*- coding:utf-8 -*-
"""
# 需要pip install pyjwt
# 直接使用django中的key当作盐
token 认证学习代码，是写项目中token认证授权的关键步骤
"""
import datetime
import jwt
from shop.settings import SECRET_KEY

# 自定义一个盐
SALT = "SADFSDAFSDFWER"


def create_token():
    headers = {
        'alg': "HS256",
        "typ": "JWT",
    }

    payload = {
        'user_id': 1,
        "username": "admin",
        "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=1)   # 定义超时时间

    }

    result = jwt.encode(headers=headers, payload=payload, key=SECRET_KEY, algorithm='HS256')
    return result


def get_payload(token):
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
    except jwt.exceptions.DecodeError:
        print("token认证失败了")
    except jwt.exceptions.ExpiredSignatureError:
        print("token已经失效了")
    except jwt.exceptions.InvalidTokenError:
        print("无效的、非法的token")


if __name__ == '__main__':
    # token = create_token()
    token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzEwMzAwOTQ2fQ.YNcvvGmGVbhBJRem8GQDudoCnStvrjfqOSbGzgMfROk"
    print(token)

    payload = get_payload(token)
    print(payload)
